package edu.stanford.prpl.app.prpltalk;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.stanford.prpl.common.PRPLConstants;
import edu.stanford.prpl.common.util.StringUtils;

public class NotificationHandlerServlet extends HttpServlet {

	private static Log log = LogFactory.getLog(NotificationHandlerServlet.class);
	private static final long serialVersionUID = 1L;

	Notification notification;

	public NotificationHandlerServlet(Notification notification) {
		this.notification = notification;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String response = (String) req.getHeader(PRPLConstants.PRPL_X_RESPONSE);

		if (StringUtils.trimEvenNull(response).equals(PRPLConstants.PRPL_X_RESPONSE_BLOB_WATCH)) {

			String values = (String) req.getHeader(PRPLConstants.PRPL_X_RESPONSE_VALUES);
			values = StringUtils.trim(values);
			String[] resourceURIs = values.split(",");

			if (resourceURIs.length > 0)
				notification.addResourceURIs(resourceURIs);

			log.debug("Notifications received.");
		}

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPost(req, resp);
	}
}
